package leetCode;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

/**
 * 5. 最长回文子串
 *
 * @author 司松坡
 * @createTime 2023年09月26日
 */
public class LeetCode5 {

    char[] charArray;
    String max = "";
    String min;
    int maxLength = 0;
    int j;
    int t;

    public String longestPalindrome(String s) {
        charArray = s.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            j = 1;
            t = 1;
            while (true) {
                if (i - j >= 0 && charArray[i - j] == charArray[i]) {
                    j++;
                } else {
                    break;
                }
            }

            while (true) {
                if (i + t < charArray.length && charArray[i + t] == charArray[i]) {
                    t++;
                } else {
                    break;
                }
            }
            min = minLongestPalindrome(j, t, i, s);
            if (min.length() > maxLength) {
                max = min;
                maxLength = min.length();
            }
        }
        return max;
    }

    private String minLongestPalindrome(int i, int j, int site, String s) {
        while (site - i >= 0 && site + j < charArray.length) {
            if (charArray[site - i] == charArray[site + j]) {
                i++;
                j++;
            } else {
                break;
            }
        }
        min = s.substring(site - i + 1, site + j);
        return min;
    }

    @Test
    public void test() {
        System.out.println(longestPalindrome("babad"));
    }


}
